﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace WebForm.WeiXinTest
{
    public partial class Test1 : System.Web.UI.Page
    {
        /// <summary>
    /// 微信平台接入URL和Token验证
    /// </summary>
    /// 

    
    private static string Token = "wei3gnet";
    protected void Page_Load(object sender, EventArgs e)
    {

        //测试时可用以下地址，然后程序会走到 Valid 方法校验后输出 原信息中的 echoStr
        //URL(服务器地址) http://test.wei3gnet.com/default.aspx?useragent=weixincode&token=wei3gnet
        //Token(令牌) wei3gnet


        string postStr =string.IsNullOrEmpty(Request.QueryString["Ueragent"])?"wei3gnet":Request.QueryString["UserAgent"];//
        Token = Request.QueryString["token"];

        if (Request.HttpMethod.ToLower() == "post")
        {
            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;

            byte[] b = new byte[s.Length];

            s.Read(b, 0, (int)s.Length);

            postStr = System.Text.Encoding.UTF8.GetString(b);

            if (!string.IsNullOrEmpty(postStr))
            {

                ResponseMsg(postStr);

                Response.Write(ResponseMsg(postStr));

                Response.End();

            }
            WriteLog("postStr:" + postStr);
        }
        else
        {


            Valid();
        }
    }

    //开发接口验证
    private void Valid()
    {

        string echoStr = Request.QueryString["echoStr"].ToString();

        if (CheckSignature())
        {

            if (!string.IsNullOrEmpty(echoStr))
            {

                Response.Write(echoStr);

                Response.End();

            }

        }

    }

    /// <summary>

    /// 验证微信签名

    /// </summary>

    /// * 将token、timestamp、nonce三个参数进行字典序排序

    /// * 将三个参数字符串拼接成一个字符串进行sha1加密

    /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。

    /// <returns></returns>

    private bool CheckSignature()
    {

        string signature = Request.QueryString["signature"].ToString();

        string timestamp = Request.QueryString["timestamp"].ToString();

        string nonce = Request.QueryString["nonce"].ToString();

        string[] ArrTmp = { Token, timestamp, nonce };

        Array.Sort(ArrTmp);     //字典排序

        string tmpStr = string.Join("", ArrTmp);

        tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

        tmpStr = tmpStr.ToLower();

        if (tmpStr == signature)
        {

            return true;

        }

        else
        {

            return false;

        }

    }


  


    /// <summary>

    /// 返回信息结果(微信信息返回)

    /// </summary>

    /// <param name="weixinXML"></param>

    private string ResponseMsg(string weixinXML)
    {

        ///这里写你的返回信息代码
        string resxml = "";


        XmlDocument doc = new XmlDocument();


        doc.LoadXml(weixinXML);


        XmlElement rootElement = doc.DocumentElement;



        XmlNode MsgType = rootElement.SelectSingleNode("MsgType");



        //RequestXML requestXML = new RequestXML();


        string ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;


        string FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;


        string CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;


        string MsgType1 = MsgType.InnerText;



        if (MsgType1 == "text")
        {


            string Content = rootElement.SelectSingleNode("Content").InnerText;

            if (Content.Trim() == "2")
            {

                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[回复内容" + Content + "]]></Content></xml>";

            }

            else if (Content.Trim() == "首页")
            {

                string url = "http://test.soshaw.com/3G/Default.aspx?name=" + FromUserName;

                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[首页]]></Title><Description><![CDATA[左岸策划--全程品牌营销策划机构]]></Description><PicUrl><![CDATA[http://test.soshaw.com/3G/img_index/center_1.gif]]></PicUrl><Url><![CDATA[" + url + "]]></Url></item></Articles></xml>";


            }
            else if (Content.Trim() == "菜单特效1")
            {

                string url = "http://test.soshaw.com/3G/1.htm?name=" + FromUserName;

                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[首页]]></Title><Description><![CDATA[左岸策划--全程品牌营销策划机构]]></Description><PicUrl><![CDATA[http://test.soshaw.com/3G/img_index/center_1.gif]]></PicUrl><Url><![CDATA[" + url + "]]></Url></item></Articles></xml>";


            }
            else
            {
                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[回复其他内容回复" + Content + "]]></Content></xml>";
            }

            System.Web.HttpContext.Current.Response.Write(resxml);

            return resxml;

        }
        else if (MsgType1 == "event")
        {
            string Event = rootElement.SelectSingleNode("Event").InnerText;
            if (Event=="subscribe")//关注事件
            {
                string openid = Request.QueryString["openid"];
                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[欢迎关注哦,关注事件！]]></Content></xml>";

                System.Web.HttpContext.Current.Response.Write(resxml);

                return resxml;
            }
            else if (Event == "unsubscribe")//取消关注
            {
                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[欢迎关注哦,取消关注事件！]]></Content></xml>";

                System.Web.HttpContext.Current.Response.Write(resxml);
                return resxml;
            }
            else
            {
                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[欢迎关注哦,取消关注事件2！]]></Content></xml>";

                System.Web.HttpContext.Current.Response.Write(resxml);

                System.Web.HttpContext.Current.Response.Write(resxml);
                return resxml;
            }
//            resxml = string.Format(@"<xml>
//<ToUserName><![CDATA[{0}]]></ToUserName>
//<FromUserName><![CDATA[{1}]]></FromUserName>
//<CreateTime>{2}</CreateTime>
//<MsgType><![CDATA[event]]></MsgType>
//<Event><![CDATA[subscribe]]></Event>
//</xml>
//", FromUserName, ToUserName, ConvertDateTimeInt(DateTime.Now));
//            System.Web.HttpContext.Current.Response.Write(resxml);
//            return resxml;
        }
        
        else
        {

            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[欢迎关注哦]]></Content></xml>";

            System.Web.HttpContext.Current.Response.Write(resxml);

            return resxml;

        }

    }



    /// <summary>

    /// unix时间转换为datetime

    /// </summary>

    /// <param name="timeStamp"></param>

    /// <returns></returns>

    private DateTime UnixTimeToTime(string timeStamp)
    {

        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

        long lTime = long.Parse(timeStamp + "0000000");

        TimeSpan toNow = new TimeSpan(lTime);

        return dtStart.Add(toNow);

    }


    /// <summary>

    /// datetime转换为unixtime

    /// </summary>

    /// <param name="time"></param>

    /// <returns></returns>

    private int ConvertDateTimeInt(System.DateTime time)
    {

        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

        return (int)(time - startTime).TotalSeconds;

    }


    /// <summary>

    /// 写日志(用于跟踪)

    /// </summary>

    private void WriteLog(string strMemo)
    {

        string filename = Server.MapPath("/logs/log.txt");

        if (!Directory.Exists(Server.MapPath("//logs//")))

            Directory.CreateDirectory("//logs//");

        StreamWriter sr = null;

        try
        {

            if (!File.Exists(filename))
            {

                sr = File.CreateText(filename);

            }

            else
            {

                sr = File.AppendText(filename);

            }

            sr.WriteLine(strMemo);

        }

        catch
        {

        }

        finally
        {

            if (sr != null)

                sr.Close();

        }

    }

}

    //    public readonly string Token = "weixin_xf";//与微信公众账号后台的Token设置保持一致，区分大小写。
    //    protected void Page_Load(object sender, EventArgs e)
    //    {

    //        //以下代码没用。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。************

    //        string signature = Request["signature"];
    //        string timestamp = Request["timestamp"];
    //        string nonce = Request["nonce"];
    //        string echostr = Request["echostr"];

    //        if (Request.HttpMethod == "GET")
    //        {
    //            //get method - 仅在微信后台填写URL验证时触发
    //            if (CheckOk(signature, timestamp, nonce, Token))
    //            {
    //                WriteContent(echostr); //返回随机字符串则表示验证通过
    //            }
    //            else
    //            {
    //                WriteContent("failed:" + signature + "," + "error"); // CheckSignature.GetSignature(timestamp, nonce, Token));
    //            }

    //        }
    //        else
    //        {
    //            //post method - 当有用户想公众账号发送消息时触发
    //            //if (!CheckSignature.Check(signature, timestamp, nonce, Token))
    //            //{
    //            //    WriteContent("参数错误！");
    //            //}

    //            ////自定义MessageHandler，对微信请求的详细判断操作都在这里面。
    //            //var messageHandler = new CustomMessageHandler(Request.InputStream, null);
    //            ////执行微信处理过程
    //            //messageHandler.Execute();
    //            ////输出结果
    //            //WriteContent(messageHandler.ResponseDocument.ToString());

    //            WriteContent("ok");
    //        }
    //        Response.End();
    //    }

    //    /// <summary>
    //    /// 进行消息认证
    //    /// </summary>
    //    /// <param name="signature"></param>
    //    /// <param name="timestamp"></param>
    //    /// <param name="nonce"></param>
    //    /// <param name="token"></param>
    //    /// <returns></returns>
    //    private bool CheckOk(string signature,string timestamp,string nonce,string token)
    //    {
    //        if (token==Token )
    //        {
    //            return true;
    //        }
    //        else
    //        {
    //            return false;
    //        }
    //    }

    //    private void WriteContent(string str)
    //    {
    //        Response.Output.Write(str);
    //    }
    //}
}